package com.itheima.sc.impl.order;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.sc.api.order.OmsOrderApi;
import com.itheima.sc.mapper.order.OmsOrderItemMapper;
import com.itheima.sc.mapper.order.OmsOrderOperateHistoryMapper;
import com.itheima.sc.mapper.order.OsmOrderMapper;
import com.itheima.sc.pojo.order.OmsOrder;
import com.itheima.sc.pojo.order.OmsOrderItem;
import com.itheima.sc.pojo.order.OmsOrderOperateHistory;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@DubboService
public class OmsOrderImpl implements OmsOrderApi {

    @Autowired
    OsmOrderMapper osmOrderMapper;
    @Autowired
    OmsOrderOperateHistoryMapper omsOrderOperateHistoryMapper;


    @Override
    public Page<OmsOrder> listOmsOrder(Integer page, Integer size, Map<String, String> map) {
        Page<OmsOrder> ipage = new Page<>(Convert.toLong(page), Convert.toLong(size));
        //订单列表
        LambdaQueryWrapper<OmsOrder> wrapper = new LambdaQueryWrapper<>();
        //订单编号
        String orderSn = map.get("orderSn");
        if (ObjectUtil.isNotEmpty(orderSn)) {
            wrapper.eq(OmsOrder::getOrderSn, orderSn);
        }
        //订单状态
        String status = map.get("status");
        if (ObjectUtil.isNotEmpty(status)) {
            wrapper.eq(OmsOrder::getStatus, Convert.toInt(status));
        }
        //订单类型
        String orderType = map.get("orderType");
        if (ObjectUtil.isNotEmpty(orderType)) {
            wrapper.eq(OmsOrder::getOrderType, Convert.toInt(orderType));
        }
        //订单来源分类
        String sourceType = map.get("sourceType");
        if (ObjectUtil.isNotEmpty(sourceType)) {
            wrapper.eq(OmsOrder::getSourceType, sourceType);
        }
        //订单收货人姓名或电话
        String receiverKeyWord = map.get("receiverKeyword");
        if (ObjectUtil.isNotEmpty(receiverKeyWord)) {
            Long idPhone = Convert.toLong(receiverKeyWord);
            if (idPhone == null) {
                //是收货人姓名
                wrapper.like(OmsOrder::getReceiverName, receiverKeyWord);
            } else {
                //是电话
                wrapper.like(OmsOrder::getReceiverPhone, idPhone);
            }
        }
        //订单提交时间
        String createTime = map.get("createTime");
        if (ObjectUtil.isNotEmpty(createTime)) {
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date parse = simpleDateFormat.parse(createTime);
                long endtime = parse.getTime() + Convert.toLong(1 * 24 * 3600 * 1000);
                Date date = new Date(endtime);
                wrapper.gt(OmsOrder::getCreateTime, parse);
                wrapper.lt(OmsOrder::getCreateTime, date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //按照一定的排序
        wrapper.orderByAsc(OmsOrder::getCreateTime);
        //分页查询条目数
        List<OmsOrder> omsOrders = osmOrderMapper.selectList(wrapper);
        System.out.println(omsOrders);
        ipage = osmOrderMapper.selectPage(ipage, wrapper);
        return ipage;

    }

    @Override
    public void deletByIds(List<Long> ids) {
        osmOrderMapper.deleteBatchIds(ids);

    }

    @Override
    public Boolean updateStatusByIds(ArrayList<Long> ids, int i, String note) {
        for (Long id : ids) {
            LambdaUpdateWrapper<OmsOrder> updateWrapper = new LambdaUpdateWrapper<>();
            OmsOrder omsOrder = new OmsOrder();
            omsOrder.setId(id);
            omsOrder.setStatus(i);//订单状态已经改变
            if (note!=null){
                omsOrder.setNote(note);
            }
            //先完成上一步
            osmOrderMapper.updateById(omsOrder);
        }
        return true;
    }

    //修改订单金额信息
    @Override
    public void updateMoneyInfo(Map<String, String> moneyInfoParam) {
        LambdaUpdateWrapper<OmsOrder> updateWrapper = new LambdaUpdateWrapper<>();
        OmsOrder updateOrder = new OmsOrder();


        //订单Id
        String orderId = moneyInfoParam.get("orderId");
        if (ObjectUtil.isNotEmpty(orderId) && !orderId.equals("")) {
            Long id = Convert.toLong(orderId);
            updateWrapper.eq(OmsOrder::getId, id);
            // 根据条件修改，订单的总金额，应付多少金额
            OmsOrder omsOrder1 = osmOrderMapper.selectById(id);
            //订单总金额
            //管理员后台调整订单所使用的的折扣金额
            String discountAmount = moneyInfoParam.get("discountAmount");
            if (ObjectUtil.isNotEmpty(discountAmount) && !discountAmount.equals("")) {
                Double updateDisCount = Convert.toDouble(discountAmount);
                updateOrder.setDiscountAmount(updateDisCount);
                Double payAmount = omsOrder1.getPayAmount();
                Double discountAmount1 = omsOrder1.getDiscountAmount();
                double nowPayAmount = payAmount + discountAmount1 - updateDisCount;
                updateOrder.setPayAmount(nowPayAmount);
            }
            //运费金额
            String freightAmount = moneyInfoParam.get("freightAmount");
            if (ObjectUtil.isNotEmpty(freightAmount) && !freightAmount.equals("")) {
                Double updateFreightAmount = Convert.toDouble(freightAmount);
                updateOrder.setFreightAmount(updateFreightAmount);
                //修改应付金额
                Double payAmount = omsOrder1.getPayAmount();
                Double freightAmount1 = omsOrder1.getFreightAmount();
                //当前有没有修改过应付金额
                if (ObjectUtil.isEmpty(updateOrder.getPayAmount())) {
                    double nowPayAmount = payAmount + (updateFreightAmount - freightAmount1);
                    updateOrder.setPayAmount(nowPayAmount);
                } else {
                    //折扣和运费的计算
                    double nowPayAmount = updateOrder.getPayAmount() + (updateFreightAmount - freightAmount1);
                    updateOrder.setPayAmount(nowPayAmount);
                }
            }

        }
        //订单状态
        String status = moneyInfoParam.get("status");
        if (ObjectUtil.isNotEmpty(status) && !status.equals("")) {
            updateWrapper.eq(OmsOrder::getStatus, Convert.toInt(status));
        }
        //修改数据库
        osmOrderMapper.update(updateOrder, updateWrapper);
    }

    //备注订单
    @Override
    public void updateNoteById(Map<String, String> map) {
        Long id = Convert.toLong(map.get("id"));
        String note = map.get("note");
        Integer status = Convert.toInt(map.get("status"));
        //备注订单
        LambdaUpdateWrapper<OmsOrder> updateWrapper = new LambdaUpdateWrapper<>();
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setNote(note);
        updateWrapper.eq(OmsOrder::getId, id);
        updateWrapper.eq(OmsOrder::getStatus, status);
        osmOrderMapper.update(omsOrder, updateWrapper);
    }

    //修改收货人信息
    @Override
    public void updateReceiverInfoById(Map<String, String> map) {
        LambdaUpdateWrapper<OmsOrder> wrapper = new LambdaUpdateWrapper<>();
        OmsOrder updateOmsOrder = new OmsOrder();
        //对象的条件
        Long orderId = Convert.toLong(map.get("orderId"));
        wrapper.eq(OmsOrder::getId, orderId);
        Integer status = Convert.toInt(map.get("status"));
        wrapper.eq(OmsOrder::getStatus, status);
        //修改值
        updateOmsOrder.setReceiverCity(map.get("receiverCity"));
        updateOmsOrder.setReceiverDetailAddress(map.get("receiverDetailAddress"));
        updateOmsOrder.setReceiverName(map.get("receiverName"));
        updateOmsOrder.setReceiverPhone(map.get("receiverPhone"));
        updateOmsOrder.setReceiverPostCode(map.get("receiverPostCode"));
        updateOmsOrder.setReceiverProvince(map.get("receiverProvince"));
        updateOmsOrder.setReceiverRegion(map.get("receiverRegion"));
        //修改信息
        osmOrderMapper.update(updateOmsOrder, wrapper);
    }

    @Override
    public OmsOrder getOrderById(Long id) {
        return osmOrderMapper.selectById(id);
    }



    @Override
    public List<OmsOrderOperateHistory> getomsOrderOperateHistories(Long orderId) {
        LambdaQueryWrapper<OmsOrderOperateHistory> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(OmsOrderOperateHistory::getOrderId, orderId);
        return omsOrderOperateHistoryMapper.selectList(queryWrapper);
    }

    @Autowired
    OmsOrderItemMapper omsOrderItemMapper;

    @Override
    public List<OmsOrderItem> getOmsOrderItem(Long orderId) {
        LambdaQueryWrapper<OmsOrderItem> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(OmsOrderItem::getOrderId, orderId);
        return omsOrderItemMapper.selectList(queryWrapper);
    }
//状态集合
    @Override
    public List<Integer> getOrderStatusByIds(List<Long> ids) {
        List<OmsOrder> omsOrders = osmOrderMapper.selectBatchIds(ids);
        return CollUtil.getFieldValues(omsOrders, "status", Integer.class);
    }
    //发货，修改配送公司，快递单号，发货时间
    @Override
    public Boolean delivery(Map<String, String> map) {
        try {
            String deliveryCompany = map.get("deliveryCompany");
            String deliverySn = map.get("deliverySn");
            OmsOrder omsOrder = new OmsOrder();
            omsOrder.setDeliveryCompany(deliveryCompany);
            omsOrder.setDeliverySn(deliverySn);
            long nowTime = System.currentTimeMillis();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parseDate = simpleDateFormat.parse(simpleDateFormat.format(new Date(nowTime)));
            omsOrder.setDeliveryTime(parseDate);
            omsOrder.setStatus(2);//已发货
            omsOrder.setId(Convert.toLong(map.get("orderId")));
            osmOrderMapper.updateById(omsOrder);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return true;
    }
//保存操作历史

    @Override
    public void addOperateHistory(OmsOrderOperateHistory omsOrderOperateHistory) {
        omsOrderOperateHistoryMapper.insert(omsOrderOperateHistory);
    }
}
